// 优雅的管理目标元素外点击事件的 Hook。

// 感觉有点问题

import { ref, onMounted, onUnmounted } from "vue";

export function useClickAway(cb: (e: MouseEvent) => any) {
  const el = ref(null);
  function _stopPropagation(e: MouseEvent) {
    e.stopPropagation()
  }
  let dom: HTMLElement;

  onMounted(() => {
    if (!el.value) return
    dom = el.value as unknown as HTMLElement;
    dom.addEventListener("click", _stopPropagation)
    document.addEventListener("click", cb);
  })
  onUnmounted(() => {
    dom.removeEventListener("click", _stopPropagation)
    document.removeEventListener("click", cb);
  })
  return el
}

export default useClickAway